package io.youngledo.usb;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.youngledo.usb.storage.StorageConfig;
import io.youngledo.usb.storage.StorageType;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

/**
 * 配置管理器 - 负责保存和加载连接配置
 */
public class ConfigManager {

    private static final String APP_DIR = ".universal-storage-browser";
    private static final String CONFIG_FILE = "connections.json";

    private final ObjectMapper objectMapper;
    private final Path configDir;
    private final Path configFile;

    public ConfigManager() {
        this.objectMapper = new ObjectMapper();

        // 获取用户主目录下的应用配置目录
        String userHome = System.getProperty("user.home");
        this.configDir = Paths.get(userHome, APP_DIR);
        this.configFile = configDir.resolve(CONFIG_FILE);

        // 确保配置目录存在
        ensureConfigDirectoryExists();
    }

    /**
     * 保存连接配置
     */
    public void saveConnection(StorageConfig config, String name) {
        try {
            List<SavedConnection> savedConnections = loadAllConnections();

            // 检查是否已存在相同名称的配置
            savedConnections.removeIf(conn -> conn.name.equals(name));

            // 添加新配置（不保存密码的明文）
            SavedConnection savedConnection = new SavedConnection(
                name,
                config.type(),
                config.endpoint(),
                config.accessKey(),
                "", // 不保存密钥的明文
                config.region(),
                config.useSSL()
            );

            savedConnections.add(savedConnection);

            // 保存到文件
            objectMapper.writerWithDefaultPrettyPrinter()
                    .writeValue(configFile.toFile(), savedConnections);

        } catch (IOException e) {
            System.err.println("Failed to save connection configuration: " + e.getMessage());
        }
    }

    /**
     * 加载所有保存的连接配置
     */
    public List<SavedConnection> loadAllConnections() {
        if (!Files.exists(configFile)) {
            return new ArrayList<>();
        }

        try {
            return objectMapper.readValue(
                configFile.toFile(),
                new TypeReference<List<SavedConnection>>() {}
            );
        } catch (IOException e) {
            System.err.println("Failed to load connection configurations: " + e.getMessage());
            return new ArrayList<>();
        }
    }

    /**
     * 删除保存的连接配置
     */
    public void deleteConnection(String name) {
        try {
            List<SavedConnection> savedConnections = loadAllConnections();
            savedConnections.removeIf(conn -> conn.name.equals(name));

            objectMapper.writerWithDefaultPrettyPrinter()
                    .writeValue(configFile.toFile(), savedConnections);

        } catch (IOException e) {
            System.err.println("Failed to delete connection configuration: " + e.getMessage());
        }
    }

    /**
     * 获取最近使用的连接配置
     */
    public SavedConnection getLastUsedConnection() {
        List<SavedConnection> connections = loadAllConnections();
        return connections.isEmpty() ? null : connections.get(connections.size() - 1);
    }

    /**
     * 根据连接名称查找保存的连接
     */
    public SavedConnection findConnectionByName(String name) {
        List<SavedConnection> connections = loadAllConnections();
        return connections.stream()
            .filter(conn -> conn.name.equals(name))
            .findFirst()
            .orElse(null);
    }

    /**
     * 确保配置目录存在
     */
    private void ensureConfigDirectoryExists() {
        try {
            if (!Files.exists(configDir)) {
                Files.createDirectories(configDir);
            }
        } catch (IOException e) {
            System.err.println("Failed to create config directory: " + e.getMessage());
        }
    }

    /**
     * 保存的连接配置数据类
     */
    public static class SavedConnection {
        public String name;
        public StorageType type;
        public String endpoint;
        public String accessKey;
        public String secretKey;  // 注意：实际不保存密码明文
        public String region;
        public boolean useSSL;

        // Jackson需要无参构造函数
        public SavedConnection() {}

        public SavedConnection(String name, StorageType type, String endpoint,
                             String accessKey, String secretKey, String region, boolean useSSL) {
            this.name = name;
            this.type = type;
            this.endpoint = endpoint;
            this.accessKey = accessKey;
            this.secretKey = secretKey;
            this.region = region;
            this.useSSL = useSSL;
        }

        /**
         * 转换为StorageConfig对象（需要用户重新输入密钥）
         */
        public StorageConfig toStorageConfig(String secretKey) {
            return new StorageConfig(type, endpoint, accessKey, secretKey, region, useSSL, null);
        }

        @Override
        public String toString() {
            return name + " (" + type.getDisplayName() + ")";
        }
    }
}